﻿using System;

using System.Windows;
using System.Windows.Data;
using Markup = System.Windows.Markup;
using Media = System.Windows.Media;

using Caliburn.Micro;


namespace DailyFx.UI
{
	/// <summary>
	///		Custom <see cref="MarkupExtension"/> used to provide <see cref="System.Windows.Controls.Image"/>, 
	///		it internally use <see cref="IUIResourceManager"/> to query the image source from named key.
	/// </summary>
	[Markup.MarkupExtensionReturnType( typeof(BindingExpression))]
	public class ImageBindingExtension : Markup.MarkupExtension
	{
		public ImageBindingExtension( string path) 
		{
			Path = path;
		}

		public ImageBindingExtension ( )
		{
		}


		[Markup.ConstructorArgument("path")]
		public string Path
		{
			get;
			set;
		}


		public override object ProvideValue ( IServiceProvider serviceProvider)
		{
			Markup.IProvideValueTarget target =
				serviceProvider.GetService(typeof(Markup.IProvideValueTarget)) as Markup.IProvideValueTarget;

			if (target.TargetObject is Setter)
			{
				return new Binding(Path) { Converter = ImageConverter.Instance };
			}
			else
			{
				Binding binding = new Binding(Path) { Converter = ImageConverter.Instance };
				return binding.ProvideValue(serviceProvider);
			}
		}
	}

	/// <summary>
	/// Custom <see cref="MarkupExtension"/> used to provide <see cref="ImageSource"/>, 
	/// it internally use <see cref="IResourceService"/> to query the image source from name key.
	/// </summary>
	[Markup.MarkupExtensionReturnType(typeof(Media.ImageSource))]
	public class Image2Extension : Markup.MarkupExtension
	{
		static ILog Log = LogManager.GetLog( typeof( Image2Extension));

		public Image2Extension( string key)
		{
			Key = key;
		}

		public Image2Extension()
		{
		}

		[Markup.ConstructorArgument("key")]
		public string Key
		{
			get;
			set;
		}

		public override object ProvideValue( IServiceProvider serviceProvider)
		{
			return IoC.Get<IUIResourceManager>().GetImage( Key);
		}
	}
}
